/**
 * Created by Tuffy on 2016/11/10.
 */
'use strict';

angular.module('driver.controllers', ['angularQFileUpload', 'LocalStorageModule'])

    .controller('IndexCtrl', ['$rootScope', '$scope', '$ionicModal', '$ionicLoading', 'IndexService', function ($rootScope, $scope, $ionicModal, $ionicLoading, IndexService) {

        $scope.cancelType = [{
            label: '司机退单',
            value: 1
        }, {
            label: '暂运或取消',
            value: 2
        }];

        // 开通用户表单
        $scope.activationUserForm = {
            phone: null
        };
        // 禁用用户表单
        $scope.disabledUserForm = {
            phone: null
        };
        // 退单表单
        $scope.cancelOrderForm = {
            orderCode: null,
            cancelreason: null,
            cancelflag: ''
        };
        // 置顶表单
        $scope.resetOrderForm = {
            message: null,
            orderCodes: null
        };
        // 修改用户表单
        $scope.exchangeUserForm = {
            message: null,
            phone: null,
            idCard: null,
            showBtn: false
        };
        // 异常回单表单
        $scope.exceptionOrderForm = {
            message: null,
            orderCodes: null
        };
        // 结算排队表单
        $scope.settlementForm = {
            phone: null,
            orderCodes: null
        };

        // 添加用户表单
        $scope.addUserForm = {
            name: null,
            phone: null,
            birthday: null,
            licenseCode: null,
            birthdayObj: new Date(),
            idCard: null,
            address: null,
            license: null,
            licenseDate: null,
            licenseDateObj: new Date()
        };

        $scope.licenseList = [];

        // 开通用户
        $ionicModal.fromTemplateUrl(contextPath + '/webpage/tms/resource/templates/modal/activation-user-modal.html', {
            scope: $scope,
            animation: 'slide-in-up'
        }).then(function (modal) {
            $scope.activationModal = modal;
        });
        $scope.openActivationModal = function () {
            $scope.activationModal.show();
        };
        $scope.closeActivationModal = function () {
            $scope.activationModal.hide();
        };

        // 添加用户
        $ionicModal.fromTemplateUrl(contextPath + '/webpage/tms/resource/templates/modal/add-user-modal.html', {
            scope: $scope,
            animation: 'slide-in-up'
        }).then(function (modal) {
            $scope.addUserModal = modal;
        });
        $scope.openAddUserModal = function () {
            $scope.addUserModal.show();
            IndexService.license().success(function (result) {
                if (result.success) {
                    $scope.licenseList = result.data;
                }
            })
        };
        $scope.closeAddUserModal = function () {
            $scope.addUserModal.hide();
            $scope.addUserForm.name = null;
            $scope.addUserForm.phone = null;
            $scope.addUserForm.birthday = null;
            $scope.addUserForm.birthdayObj = new Date();
            $scope.addUserForm.licenseCode = null;
            $scope.addUserForm.idCard = null;
            $scope.addUserForm.address = null;
            $scope.addUserForm.license = null;
            $scope.addUserForm.licenseDate = null;
            $scope.addUserForm.licenseDateObj = new Date();
        };

        // 禁用用户
        $ionicModal.fromTemplateUrl(contextPath + '/webpage/tms/resource/templates/modal/disabled-user-modal.html', {
            scope: $scope,
            animation: 'slide-in-up'
        }).then(function (modal) {
            $scope.disabledModal = modal;
        });
        $scope.openDisabledModal = function () {
            $scope.disabledModal.show();
        };
        $scope.closeDisabledModal = function () {
            $scope.disabledModal.hide();
        };

        // 退单
        $ionicModal.fromTemplateUrl(contextPath + '/webpage/tms/resource/templates/modal/cancel-user-modal.html', {
            scope: $scope,
            animation: 'slide-in-up'
        }).then(function (modal) {
            $scope.cancelModal = modal;
        });
        $scope.openCancelModal = function () {
            $scope.cancelModal.show();
        };
        $scope.closeCancelModal = function () {
            $scope.cancelModal.hide();
        };

        // 置顶
        $ionicModal.fromTemplateUrl(contextPath + '/webpage/tms/resource/templates/modal/reset-order-modal.html', {
            scope: $scope,
            animation: 'slide-in-up'
        }).then(function (modal) {
            $scope.resetOrderModal = modal;
        });
        $scope.openResetOrderModal = function () {
            $scope.resetOrderModal.show();
        };
        $scope.closeResetOrderModal = function () {
            $scope.resetOrderForm.orderCodes = null;
            $scope.resetOrderForm.message = null;
            $scope.resetOrderModal.hide();
        };

        // 修改用户
        $ionicModal.fromTemplateUrl(contextPath + '/webpage/tms/resource/templates/modal/exchange-user-modal.html', {
            scope: $scope,
            animation: 'slide-in-up'
        }).then(function (modal) {
            $scope.exchangeUserModal = modal;
        });
        $scope.openExchangeUserModal = function () {
            $scope.exchangeUserModal.show();
        };
        $scope.closeExchangeUserModal = function () {
            $scope.exceptionOrderForm.phone = null;
            $scope.exceptionOrderForm.message = null;
            $scope.exceptionOrderForm.idCard = null;
            $scope.exchangeUserModal.hide();
        };

        // 异常订单
        $ionicModal.fromTemplateUrl(contextPath + '/webpage/tms/resource/templates/modal/exception-order-modal.html', {
            scope: $scope,
            animation: 'slide-in-up'
        }).then(function (modal) {
            $scope.exceptionOrderModal = modal;
        });
        $scope.openExceptionOrderModal = function () {
            $scope.exceptionOrderModal.show();
        };
        $scope.closeExceptionOrderModal = function () {
            $scope.exceptionOrderModal.orderCodes = null;
            $scope.exceptionOrderModal.message = null;
            $scope.exceptionOrderModal.hide();
        };

        // 结算排队
        $ionicModal.fromTemplateUrl(contextPath + '/webpage/tms/resource/templates/modal/settlement-user-modal.html', {
            scope: $scope,
            animation: 'slide-in-up'
        }).then(function (modal) {
            $scope.settlementModal = modal;
        });
        $scope.openSettlementModal = function () {
            $scope.settlementModal.show();
        };
        $scope.closeSettlementModal = function () {
            $scope.settlementForm.phone = null;
            $scope.settlementForm.orderCodes = null;
            $scope.settlementModal.hide();
        };

        // 添加用户提交
        $scope.addUserBtn = function () {
            $ionicLoading.show({
                template: '加载中...'
            });
            $scope.addUserForm.licenseDate = $scope.addUserForm.licenseDateObj.format($scope.addUserForm.licenseDateObj.YYYY_MM_DD_HH_MM_SS);
            $scope.addUserForm.birthday = $scope.addUserForm.licenseDateObj.format($scope.addUserForm.licenseDateObj.YYYY_MM_DD_HH_MM_SS);
            IndexService.addUser($scope.addUserForm)
                .success(function (result) {
                    if (result.success) {
                        $rootScope.FIREFLY.toast({
                            title: '用户添加成功',
                            okCallback: function () {
                                $scope.closeAddUserModal();
                            }
                        });
                    } else {
                        $rootScope.FIREFLY.toast({
                            title: result.message
                        });
                    }
                })
                .finally(function () {
                    $ionicLoading.hide();
                });
        }

        // 开通用户提交
        $scope.activationUserBtn = function () {
            if (!$scope.activationUserForm.phone) {
                $rootScope.FIREFLY.toast({
                    title: '数据不可为空'
                });
                return;
            }
            $ionicLoading.show({
                template: '加载中...'
            });
            IndexService.activationUser($scope.activationUserForm.phone)
                .success(function (result) {
                    if (result.success) {
                        $rootScope.FIREFLY.toast({
                            title: '用户开通成功',
                            okCallback: function () {
                                $scope.closeActivationModal();
                            }
                        });
                    } else {
                        $rootScope.FIREFLY.toast({
                            title: result.message
                        });
                    }
                })
                .finally(function () {
                    $ionicLoading.hide();
                });
        }

        // 禁用用户提交
        $scope.disabledUserBtn = function () {
            if (!$scope.disabledUserForm.phone) {
                $rootScope.FIREFLY.toast({
                    title: '数据不可为空'
                });
                return;
            }
            $ionicLoading.show({
                template: '加载中...'
            });
            IndexService.disabledUser($scope.disabledUserForm.phone)
                .success(function (result) {
                    if (result.success) {
                        $rootScope.FIREFLY.toast({
                            title: '用户禁用成功',
                            okCallback: function () {
                                $scope.closeDisabledModal();
                            }
                        });
                    } else {
                        $rootScope.FIREFLY.toast({
                            title: result.message
                        });
                    }
                })
                .finally(function () {
                    $ionicLoading.hide();
                });
        }

        // 退单提交
        $scope.cancelOrderBtn = function () {
            if (!$scope.cancelOrderForm.orderCode) {
                $rootScope.FIREFLY.toast({
                    title: '订单不可为空'
                });
                return;
            }
            if (!$scope.cancelOrderForm.cancelflag) {
                $rootScope.FIREFLY.toast({
                    title: '取消类型不可为空'
                });
                return;
            }
            if (!$scope.cancelOrderForm.cancelreason) {
                $rootScope.FIREFLY.toast({
                    title: '取消原因不可为空'
                });
                return;
            }
            $ionicLoading.show({
                template: '加载中...'
            });
            IndexService.cancelOrder($scope.cancelOrderForm)
                .success(function (result) {
                    if (result.success) {
                        $rootScope.FIREFLY.toast({
                            title: '退单成功',
                            okCallback: function () {
                                $scope.closeCancelModal();
                            }
                        });
                    } else {
                        $rootScope.FIREFLY.toast({
                            title: result.message
                        });
                    }
                })
                .finally(function () {
                    $ionicLoading.hide();
                });
        }

        // 置顶提交
        $scope.resetOrderBtn = function () {
            $scope.resetOrderForm.message = null;
            if (!$scope.resetOrderForm.orderCodes) {
                $rootScope.FIREFLY.toast({
                    title: '数据不可为空'
                });
                return;
            }
            $ionicLoading.show({
                template: '加载中...'
            });
            IndexService.resetOrder($scope.resetOrderForm.orderCodes)
                .success(function (result) {
                    if (result.success) {
                        $scope.resetOrderForm.message = result.data;
                        $rootScope.FIREFLY.toast({
                            title: '置顶成功'
                        });
                    } else {
                        $rootScope.FIREFLY.toast({
                            title: result.message
                        });
                    }
                })
                .finally(function () {
                    $ionicLoading.hide();
                });
        }

        // 修改用户手机号句柄
        $scope.exchangeUserHandler = {
            blurCheck: function () {
                IndexService.idnoOrder($scope.exchangeUserForm.idCard)
                    .success(function (result) {
                        $scope.exchangeUserForm.message = result.data;
                        if (result.success) {
                            $scope.exchangeUserForm.showBtn = true;
                        } else {
                            $scope.exchangeUserForm.showBtn = false;
                        }
                    })
            },
            exchangeUserBtn: function () {
                if (!$scope.exchangeUserForm.showBtn) {
                    return;
                }
                if (!$rootScope.FIREFLY.isMobile($scope.exchangeUserForm.phone)) {
                    $scope.exchangeUserForm.message = '手机号不合法';
                    return;
                }
                IndexService.exchangeOrder($scope.exchangeUserForm.idCard, $scope.exchangeUserForm.phone)
                    .success(function (result) {
                        if (result.success) {
                            $rootScope.FIREFLY.toast({
                                title: '修改成功',
                                okCallback: function () {
                                    $scope.closeExchangeUserModal();
                                }
                            });
                        } else {
                            $rootScope.FIREFLY.toast({
                                title: result.message
                            });
                        }
                    });
            }
        }

        // 异常回单提交
        $scope.exceptionOrderBtn = function () {
            $scope.exceptionOrderForm.message = null;
            if (!$scope.exceptionOrderForm.orderCodes) {
                $rootScope.FIREFLY.toast({
                    title: '数据不可为空'
                });
                return;
            }
            $ionicLoading.show({
                template: '加载中...'
            });
            IndexService.exceptionOrder($scope.exceptionOrderForm.orderCodes)
                .success(function (result) {
                    if (result.success) {
                        $scope.exceptionOrderForm.message = '成功数据：' + result.data;
                        $rootScope.FIREFLY.toast({
                            title: '处理成功'
                        });
                    } else {
                        $rootScope.FIREFLY.toast({
                            title: result.message
                        });
                    }
                })
                .finally(function () {
                    $ionicLoading.hide();
                });
        }

        // 结算排队
        $scope.settlementOrderBtn = function () {
            if (!$scope.settlementForm.phone) {
                $rootScope.FIREFLY.toast({
                    title: '手机号不可为空'
                });
                return;
            }
            if (!$scope.settlementForm.orderCodes) {
                $rootScope.FIREFLY.toast({
                    title: '订单号不可为空'
                });
                return;
            }
            $ionicLoading.show({
                template: '加载中...'
            });
            IndexService.receipt($scope.settlementForm)
                .success(function (result) {
                    if (result.success) {
                        $rootScope.FIREFLY.toast({
                            title: '处理成功'
                        });
                    } else {
                        $rootScope.FIREFLY.toast({
                            title: result.message
                        });
                    }
                })
                .finally(function () {
                    $ionicLoading.hide();
                });
        }

        // 登出提交
        $scope.logout = function () {
            IndexService.logout().success(function (result) {
                if (result.success) {
                    location.href = contextPath + '/zl';
                } else {
                    $rootScope.FIREFLY.toast({
                        title: result.message
                    });
                }
            });
        }

    }])

    .controller('OrdersCtrl', ['$rootScope', '$scope', '$state', 'IndexService', function ($rootScope, $scope, $state, IndexService) {
        $scope.list = [];
        IndexService.orderList().success(function (result) {
            if (result.success) {
                $scope.list = result.data;
            } else {
                $scope.list = [];
                $rootScope.FIREFLY.toast({
                    title: result.message,
                    okCallback: function () {
                        $state.go('index');
                    }
                });
            }
        });
    }])

    .controller('DriversCtrl', ['$rootScope', '$scope', '$state', 'IndexService', function ($rootScope, $scope, $state, IndexService) {
        $scope.list = [];
        IndexService.driverList().success(function (result) {
            if (result.success) {
                $scope.list = result.data;
            } else {
                $scope.list = [];
                $rootScope.FIREFLY.toast({
                    title: result.message,
                    okCallback: function () {
                        $state.go('index');
                    }
                });
            }
        });
    }])

    .controller('ChargeBackCtrl', ['$rootScope', '$scope', '$state', 'IndexService', function ($rootScope, $scope, $state, IndexService) {
        $scope.list = [];
        $scope.searchForm = {
            orderCode: null
        };
        $scope.init = function () {
            IndexService.chargebackList($scope.searchForm.orderCode).success(function (result) {
                if (result.success) {
                    $scope.list = result.data;
                } else {
                    $scope.list = [];
                    $rootScope.FIREFLY.toast({
                        title: result.message,
                        okCallback: function () {
                            $state.go('index');
                        }
                    });
                }
            });
        };

        // 清空条件查询
        $scope.keyupEvent = function () {
            if (!$scope.searchForm.orderCode) {
                $scope.init();
            }
        };

        // 重新入队
        $scope.orderEnqueue = function (orderCode) {
            IndexService.addOrderToRedis({orderCode: orderCode}).success(function (result) {
                if (result.success) {
                    // 重新初始化退单列表
                    $rootScope.FIREFLY.toast({
                        title: '入队成功',
                        okCallback: function () {
                            $scope.init();
                        }
                    });
                } else {
                    $rootScope.FIREFLY.toast({
                        title: result.message
                    });
                }
            })
        };
        // 初始化
        $scope.init();
    }])

    .controller('QueryOrderCtrl', ['$rootScope', '$scope', 'IndexService', function ($rootScope, $scope, IndexService) {

        $scope.orderObj = '';

        $scope.searchForm = {
            orderCode: ''
        };

        // 初始化数据
        $scope.init = function () {
            if ($scope.searchForm.orderCode == '') {
                $rootScope.FIREFLY.toast({
                    title: '订单号不能为空'
                });
                return;
            }
            IndexService.queryOrder($scope.searchForm.orderCode).success(function (result) {
                if (result.success) {
                    $scope.orderObj = result.data;
                    if ($scope.orderObj.id == -1 && $scope.orderObj.status == 100) {
                        $scope.orderObj.statusText = '退单';
                    }
                    $scope.searchForm.orderCode = '';
                } else {
                    $scope.orderObj = '';
                    $rootScope.FIREFLY.toast({
                        title: result.message
                    });
                }
            });
        };

        // 清空条件查询
        $scope.keyupEvent = function () {
            if (!$scope.searchForm.orderCode) {
                $scope.init();
            }
        };
    }])

    .controller('UserPhotoCtrl', ['$rootScope', '$scope', '$log', '$qupload', 'QiniuService', 'IndexService', function ($rootScope, $scope, $log, $qupload, QiniuService, IndexService) {

        $scope.queryUser = {
            phone: ''
        };

        $scope.userList = [];

        $scope.isShow = false;

        $scope.isShowBtn = false;

        $scope.selectFiles = [];

        // 初始化数据
        $scope.init = function () {
            if ($scope.queryUser.phone == '') {
                $scope.userList = [];
                $scope.isShowBtn = false;
                return;
            }
            IndexService.userList($scope.queryUser.phone).success(function (result) {
                if (result.success) {
                    $scope.userList = result.data;
                    if ($scope.userList != '' && $scope.userList != null) {
                        if ($scope.userList.length > 0) {
                            $scope.isShowBtn = true;
                        }
                    }
                } else {
                    $scope.userList = [];
                    $rootScope.FIREFLY.toast({
                        title: result.message
                    });
                }
            });
        };

        function savePic(id, pic, imgUrl) {
            IndexService.savePic({
                id: id,
                pic: pic
            }).success(function (result) {
                if (result.success) {
                    $scope.init();
                } else {
                    $rootScope.FIREFLY.toast({
                        title: result.message
                    });
                }
            })
        }

        function getToken() {
            QiniuService.getUploadQiniuToken().success(function (result) {
                if (result.success) {
                    $scope.token = result.data;
                }
            });
        }

        function loadPic(key) {
            QiniuService.getDownloadQiniuTicket(key).success(function (result) {
                if (result.success) {
                    $scope.userList[0].image = result.data;
                    // 保存图片到数据库
                    savePic($scope.dId, key);
                }
                $scope.isShow = false;
            });
        }

        var start = function (index) {
            $scope.selectFiles[index].progress = {
                p: 0
            };
            var fileName = new Date().getTime() + $scope.selectFiles[index].file.name;
            $scope.selectFiles[index].upload = $qupload.upload({
                key: fileName,
                file: $scope.selectFiles[index].file,
                token: $scope.token
            });
            $scope.selectFiles[index].upload.then(function (response) {
                $log.info(response.hash);
                // 加载上传的图片
                loadPic(fileName);
            }, function (response) {
                $log.info(response.key);
            }, function (evt) {
                $scope.selectFiles[index].progress.p = Math.floor(100 * evt.loaded / evt.totalSize);
            });
        };

        $scope.abort = function (index) {
            $scope.selectFiles[index].upload.abort();
            $scope.selectFiles.splice(index, 1);
        };

        $scope.onFileSelect = function ($files) {
            $scope.dId = $scope.userList[0].dId;
            $scope.isShow = true;
            if ($scope.token == '') {
                $rootScope.FIREFLY.toast({
                    title: '网络异常,请刷新页面重试'
                });
                return;
            }
            var offsetx = $scope.selectFiles.length;
            for (var i = 0; i < $files.length; i++) {
                $scope.selectFiles[i + offsetx] = {
                    file: $files[i]
                };
                start(i + offsetx);
            }
        };

        getToken();
        $scope.init();

    }])